//
//  HMUserAcountViewModel.swift
//  weibo10
//
//  Created by mac on 15/10/20.
//  Copyright © 2015年 itheima. All rights reserved.
//

import Foundation

class HMUserAcountViewModel {
    
    // 单例 ： 避免重复从沙盒中 获取归档文件，提高效率，便于拿到token值
    static let sharedUserAccount = HMUserAcountViewModel()
    
    ///返回有效的token值
    var token: String?{
        return isExpired ? nil : userAccount?.access_token
    }
    var userAccount: HMUserAccount?
    // 
    var userLogon: Bool{
        
        return userAccount?.access_token != nil && !isExpired
    }
    // 头像属性
    var iconUrl:NSURL{
        return NSURL(string: userAccount?.avatar_large ?? "")!
    }
    private var accountPath: String{
        var path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last!
        path = (path as NSString).stringByAppendingPathComponent("account.plist")
        return path
    }
    private var isExpired: Bool{
        if userAccount?.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
            return false
        }
        return true
    }
    init(){
        // 解档
        userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? HMUserAccount
        print(isExpired)
        // 判断是否过期
        if isExpired {
            print("已过期")
            userAccount = nil
        }
        print(userAccount)
    }
}
// MARK -封装网络
extension HMUserAcountViewModel{
    func loadAccessToken(code:String,finished:(isSuccess:Bool) -> ()){
        // 通过code（授权码）去换取token
        NetworkTools.sharedTools.getToken(code) { (result, error) -> () in
            if error != nil {
                print("获取失败")
                finished(isSuccess: false)
                return
            }
            
            self.userAccount = HMUserAccount(dict: result as! [String: AnyObject])
            
            self.loadUserInfo(self.userAccount!, finished: finished)
        }
        

    }
 private func loadUserInfo(account:HMUserAccount,finished:(isSuccess:Bool) -> ()){
    NetworkTools.sharedTools.loadUserInfo(account.uid!) { (result, error) -> () in
        if error != nil {
            finished(isSuccess: false)
            return
        }
        guard let dict = result as? [String: AnyObject] else{
            finished(isSuccess: false)
            return
        }
        
        account.screen_name = dict["screen_name"] as? String
        account.avatar_large = dict["avatar_large"] as?String
        print(account)
        // 将用户信息归档保存
        account.saveUserAccount()
        finished(isSuccess: true)
    }
}
}